package com.ly.service.house;

import com.google.common.collect.Maps;
import com.ly.base.*;
import com.ly.entity.*;
import com.ly.repository.*;
import com.ly.service.ServiceMultiResult;
import com.ly.service.ServiceResult;
import com.ly.service.search.ISearchService;
import com.ly.web.dto.HouseDTO;
import com.ly.web.dto.HouseDetailDTO;
import com.ly.web.dto.HousePictureDTO;
import com.ly.web.dto.HouseSubscribeDTO;
import com.ly.web.form.*;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @author ：LY
 * @date ：Created in 2020/11/14 22:14
 * @modified By：
 */
@Service
public class HouseServiceImpl implements IHouseService{

    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private HouseRepository houseRepository;

    @Autowired
    private HouseDetailRepository houseDetailRepository;

    @Autowired
    private HousePictureRepository housePictureRepository;

    @Autowired
    private HouseTagRepository houseTagRepository;

    @Autowired
    private SubwayRepository subwayRepository;
    @Autowired
    private SubwayStationRepository subwayStationRepository;

    @Autowired
    private IQiNiuService qiNiuService;

    @Autowired
    private ISearchService searchService;

    @Autowired
    private HouseSubscribeRespository houseSubscribeRespository;


    @Value("${qiniu.cdn.prefix}")
    private String cdnPrefix;

    @Override
    public ServiceMultiResult<HouseDTO> wholeMapQuery(MapSearch mapSearch) {
        ServiceMultiResult<Long> serviceResult = searchService.mapQuery(mapSearch.getCityEnName(), mapSearch.getOrderBy(), mapSearch.getOrderDirection(), mapSearch.getStart(), mapSearch.getSize());
        if (serviceResult.getTotal() == 0){
            return new ServiceMultiResult<>(0,new ArrayList<>());
        }
        List<HouseDTO> houseDTOS = wrapperHouseResult(serviceResult.getResult());

        return new ServiceMultiResult<>(serviceResult.getTotal(),houseDTOS);
    }

    /**
     * 房源信息保存
     * @param houseForm
     * @return
     */
    @Override
    public ServiceResult<HouseDTO> save(HouseForm houseForm) {
        HouseDetail detail = new HouseDetail();
        ServiceResult<HouseDTO> subwayValidtionResult = wrapperDetailInfo(detail,houseForm);
      if (subwayValidtionResult != null){
          return subwayValidtionResult;
      }

        //保存主体信息
        House house = new House();
        modelMapper.map(houseForm,house);
        Date now = new Date();
        house.setCreateTime(now);
        house.setLastUpdateTime(now);
        house.setAdminId(LoginUserUtil.getLoginUserId());
        houseRepository.save(house);
        detail.setHouseId(house.getId());
        detail = houseDetailRepository.save(detail);
        //图片保存
        List<HousePicture> pictures = generatePictures(houseForm,house.getId());
        Iterable<HousePicture> housePictures = housePictureRepository.save(pictures);

       HouseDTO  houseDTO = modelMapper.map(house,HouseDTO.class);
        HouseDetailDTO houseDetailDTO = modelMapper.map(detail,HouseDetailDTO.class);
        houseDTO.setHouseDetail(houseDetailDTO);
        List<HousePictureDTO> pictureDTOS = new ArrayList<>();
        housePictures.forEach(housePicture -> pictureDTOS.add(modelMapper.map(housePicture,HousePictureDTO.class)));
        houseDTO.setPictures(pictureDTOS);
        houseDTO.setCover(this.cdnPrefix+houseDTO.getCover());

        List<String> tags = houseForm.getTags();
        if (tags != null || !tags.isEmpty()){
            List<HouseTag> houseTags = new ArrayList<>();
            for (String tag : tags) {
                houseTags.add(new HouseTag(house.getId(),tag));
            }
            houseTagRepository.save(houseTags);
            houseDTO.setTags(tags);
        }
        return new ServiceResult<HouseDTO>(true,null,houseDTO);
    }

    @Override
    @Transactional
    public ServiceResult update(HouseForm houseForm) {
        House house = this.houseRepository.findOne(houseForm.getId());
        if (house == null){

            return ServiceResult.notFound();
        }
        HouseDetail detail = this.houseDetailRepository.findByHouseId(house.getId());
        if (detail == null){
            return ServiceResult.notFound();
        }

        ServiceResult wrapperResult = wrapperDetailInfo(detail,houseForm);
        if (wrapperResult != null){
            return wrapperResult;
        }
        houseDetailRepository.save(detail);

        List<HousePicture> pictures = generatePictures(houseForm,houseForm.getId());
        housePictureRepository.save(pictures);

        if (houseForm.getCover() == null){
            houseForm.setCover(house.getCover());
        }
        modelMapper.map(houseForm,house);
        house.setLastUpdateTime(new Date());
        houseRepository.save(house);
        if (house.getStatus() == HouseStatus.PASSES.getValue()){
            searchService.index(house.getId());
        }

        return ServiceResult.success();
    }

    /**
     * 管理员房源浏览主要方法，主要是两个类 一个排序分页的Pageable 一个是查询对象Specification.
     * @param searchBody
     * @return
     */
    @Override
    public ServiceMultiResult<HouseDTO> adminQuery(DatatableSearch searchBody) {

        List<HouseDTO> houseDTOS = new ArrayList<>();
        //searchBody.getDirection())指定是升序还是降序，后面那个字段指定按什么排序
        Sort sort = new Sort(Sort.Direction.fromString(searchBody.getDirection()),searchBody.getOrderBy());
        //获取当前是第几页
        int page  = searchBody.getStart()/searchBody.getLength();
        //查询对象  第一个参数第几页 第二 一页多长 第三排序
        Pageable pageable = new PageRequest(page,searchBody.getLength(),sort);


        /**
         *    *   root    ：Root接口，代表查询的根对象，可以通过root获取实体中的属性
         *     *   query   ：代表一个顶层查询对象，用来自定义查询
         *     *   cb      ：用来构建查询，此对象里有很多条件方法
         *
         */
        //对参数进行一些封装，进行各种维度的查询操作
        Specification<House> specification = (root,query,cb) ->{
            //当前用户的房源信息
            Predicate predicate = cb.equal(root.get("adminId"),LoginUserUtil.getLoginUserId());
            //只能查到未删除过的房源信息
            predicate = cb.and(predicate,cb.notEqual(root.get("status"), HouseStatus.DELETED.getValue()));
            if (searchBody.getCity() != null){
                predicate = cb.and(predicate,cb.equal(root.get("cityEnName"),searchBody.getCity()));
            }
            if (searchBody.getStatus() !=  null){
                predicate  = cb.and(predicate,cb.equal(root.get("status"),searchBody.getStatus()));
            }
            if (searchBody.getCreateTimeMin() != null){
                predicate = cb.and(predicate,cb.greaterThanOrEqualTo(root.get("createTime"),searchBody.getCreateTimeMin()));
            }
            if (searchBody.getCreateTimeMax() != null){
                predicate = cb.and(predicate,cb.lessThanOrEqualTo(root.get("createTime"),searchBody.getCreateTimeMax()));
            }
            if (searchBody.getTitle() != null){
                predicate  =cb.and(predicate,cb.like(root.get("title"),"%"+searchBody.getTitle()+"%"));
            }
            return predicate;
        };
        //通过内置的findAll方法，传入一个查询对象和一个排序分页对象，返回Page
        Page<House> houses = houseRepository.findAll(specification,pageable);
        houses.forEach(house -> {
            HouseDTO houseDTO = modelMapper.map(house,HouseDTO.class);
            houseDTO.setCover(this.cdnPrefix + house.getCover());
            houseDTOS.add(houseDTO);
        });

        return new ServiceMultiResult<>(houses.getTotalElements(),houseDTOS);
    }

    /**
     * 查询一个房源的完整信息，完成房源展示功能
     * @param id
     * @return
     */
    @Override
    public ServiceResult<HouseDTO> findCompleteOne(Long id) {
        //查询一个房源的完整信息，完成房源展示功能
        House house = houseRepository.findOne(id);
        if (house == null){
            return ServiceResult.notFound();
        }
        //查询房源详细信息
        HouseDetail detail = houseDetailRepository.findByHouseId(id);
        //查询房源信息的图片
        List<HousePicture> pictures = housePictureRepository.findAllByHouseId(id);
        //封装转换
        HouseDetailDTO houseDetailDTO = modelMapper.map(detail,HouseDetailDTO.class);
        List<HousePictureDTO> pictureDTOS = new ArrayList<>();
        for (HousePicture picture : pictures) {
            HousePictureDTO pictureDTO = modelMapper.map(picture,HousePictureDTO.class);
            pictureDTOS.add(pictureDTO);
        }
        //通过id查询所有标签信息
        List<HouseTag> tags = houseTagRepository.findAllByHouseId(id);
        List<String> tagList = new ArrayList<>();
        for (HouseTag tag : tags) {
            tagList.add(tag.getName());
        }
        HouseDTO result = modelMapper.map(house,HouseDTO.class);
        result.setHouseDetail(houseDetailDTO);
        result.setPictures(pictureDTOS);
        result.setTags(tagList);
        if (LoginUserUtil.getLoginUserId()>0){
            //已登录用户才能进行操作 查询预约数据
            HouseSubscribe byHouseIdAndUserId = houseSubscribeRespository.findByHouseIdAndUserId(house.getId(), LoginUserUtil.getLoginUserId());
            if (byHouseIdAndUserId!=null){
                result.setSubscribeStatus(byHouseIdAndUserId.getStatus());
            }
        }
        ServiceResult<HouseDTO> serviceResult = ServiceResult.of(result);
        return serviceResult;
    }

    @Override
    public ServiceResult removePhoto(Long id) {
        HousePicture picture = housePictureRepository.findOne(id);
        if (picture == null){
            return ServiceResult.notFound();
        }
        try {
            Response response = this.qiNiuService.delete(picture.getPath());
            if (response.isOK()){
                housePictureRepository.delete(id);
                return ServiceResult.success();
            }else{
                return new ServiceResult(false,response.error);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            return new ServiceResult(false,e.getMessage());
        }

    }

    /**
     * 更新封面
     * @param coverId 图片ID
     * @param targetId 房屋ID
     * @return
     */
    @Override
    @Transactional
    public ServiceResult updateCover(Long coverId, Long targetId) {
        //更新封面
        HousePicture cover = housePictureRepository.findOne(coverId);
        if (cover == null){
            return ServiceResult.notFound();
        }
        houseRepository.updateCover(targetId,cover.getPath());
        return ServiceResult.success();
    }

    @Override
    public ServiceResult addTag(Long houseId, String tag) {
        House house = houseRepository.findOne(houseId);
        if (house == null){
            return ServiceResult.notFound();
        }
        HouseTag houseTag = houseTagRepository.findByNameAndHouseId(tag, houseId);
        if (houseTag != null){
            return new ServiceResult(false,"标签已存在!");
        }
        houseTagRepository.save(new HouseTag(houseId,tag));
        return ServiceResult.success();
    }

    @Override
    public ServiceResult removeTag(Long houseId, String tag) {
        House house = houseRepository.findOne(houseId);
        if (house == null) {
            return ServiceResult.notFound();
        }

        HouseTag houseTag = houseTagRepository.findByNameAndHouseId(tag, houseId);
        if (houseTag == null) {
            return new ServiceResult(false, "标签不存在");
        }

        houseTagRepository.delete(houseTag.getId());
        return ServiceResult.success();
    }

    @Override
    @Transactional
    public ServiceResult updateStatus(Long id, int status) {
        House house = houseRepository.findOne(id);
        if (house == null){
            return ServiceResult.notFound();
        }
        //验证
        if (house.getStatus() == status){
            return  new ServiceResult(false,"状态为发生变化");
        }
        if (house.getStatus() == HouseStatus.RENTED.getValue()){
            return new ServiceResult(false,"已出租的房源不允许修改状态");

        }
        if (house.getStatus() == HouseStatus.DELETED.getValue()){
            return new ServiceResult(false,"已删除的资源不允许操作");
        }
        houseRepository.updateStatus(id, status);
        //只有上架更新索引  其他情况删除索引

        if (status == HouseStatus.PASSES.getValue()){
            searchService.index(id);
        }else {
            searchService.remove(id);
        }
        return ServiceResult.success();
    }

    //query方法，走es查询出houseid时,查询房源数据
    private List<HouseDTO> wrapperHouseResult(List<Long> houseId){
        List<HouseDTO> result = new ArrayList<>();
        //id和housedto进行结果映射
        Map<Long,HouseDTO> idToHouseMap = new HashMap<>();
        Iterable<House> houses = houseRepository.findAll(houseId);
        houses.forEach(
                house -> {
                    //排除掉非上架状态的房源信息
//                   if (house.getStatus()==HouseStatus.PASSES.getValue()){
                        HouseDTO houseDTO = modelMapper.map(house,HouseDTO.class);
                        houseDTO.setCover(this.cdnPrefix + house.getCover());
                        idToHouseMap.put(house.getId(),houseDTO);
//                    }else {
//                        houseId.remove(houseId.indexOf(house.getId()));//这步非常损耗性能，需要优化
//                    }

                }
        );
        //通过houseid将全部的housedetail的数据映射到housedto中
        wrapperHouseList(houseId,idToHouseMap);

        //矫正顺序，es查到的id和数据库的数据不一定相同
        for (Long Id:houseId){
            result.add(idToHouseMap.get(Id));
        }
        return result;
    }
    @Override
    public ServiceMultiResult<HouseDTO> query(RentSearch rentSearch) {
        //有任意一个条件都进行es的查询
        if ((rentSearch.getKeywords() != null && !rentSearch.getKeywords().isEmpty())||(rentSearch.getRoom()!=0)||rentSearch.getRegionEnName()!=null||(!RentValueBlock.All.equals(rentSearch.getPriceBlock())&&rentSearch.getPriceBlock()!=null)||(!RentValueBlock.All.equals(rentSearch.getAreaBlock())&&rentSearch.getAreaBlock()!=null)||rentSearch.getRentWay()!=-1||rentSearch.getDirection()!=0){
            //走searchService的query,查出房源的id
            ServiceMultiResult<Long> serviceResult = searchService.query(rentSearch);

            if (serviceResult.getTotal() == 0){
                return new ServiceMultiResult<>(0,new ArrayList<>());
            }
            List<HouseDTO> houseDTOS = wrapperHouseResult(serviceResult.getResult());
            return new ServiceMultiResult<>(serviceResult.getTotal(),houseDTOS);
//            return new ServiceMultiResult<>(houseDTOS.size(),houseDTOS);
        }
//        Sort sort = new Sort(Sort.Direction.DESC,"lastUpdateTime");
        return simpleQuery(rentSearch);
    }

    @Override
    public ServiceMultiResult<HouseDTO> boundMapQuery(MapSearch mapSearch) {
        ServiceMultiResult<Long> serviceMultiResult = searchService.mapQuery(mapSearch);
        if (serviceMultiResult.getTotal()==0){
            return new ServiceMultiResult<>(0,new ArrayList<>());

        }
        List<HouseDTO> houseDTOS = wrapperHouseResult(serviceMultiResult.getResult());
        return new ServiceMultiResult<>(serviceMultiResult.getTotal(),houseDTOS);
    }

    @Override
    public ServiceMultiResult<HouseDTO> districtMapQuery(MapSearchDistrict mapSearch) {
        ServiceMultiResult<Long> serviceMultiResult = searchService.mapQuery(mapSearch);
        if (serviceMultiResult.getTotal()==0){
            return new ServiceMultiResult<>(0,new ArrayList<>());

        }
        List<HouseDTO> houseDTOS = wrapperHouseResult(serviceMultiResult.getResult());
        return new ServiceMultiResult<>(serviceMultiResult.getTotal(),houseDTOS);
    }
    @Override
    @Transactional
    public ServiceResult addSubscribeOrder(Long houseId) {
        Long userId = LoginUserUtil.getLoginUserId();
        HouseSubscribe subscribe = houseSubscribeRespository.findByHouseIdAndUserId(houseId, userId);
        if (subscribe!=null){
            return new ServiceResult(false,"已加入预约");
        }
        House house = houseRepository.findOne(houseId);
        if (house==null){
            return new ServiceResult(false,"查无此房");
        }
        subscribe= new HouseSubscribe();
        Date now = new Date();
        subscribe.setCreateTime(now);
        subscribe.setLastUpdateTime(now);
        subscribe.setUserId(userId);
        subscribe.setHouseId(houseId);
        subscribe.setStatus(HouseSubscribeStatus.IN_ORDER_LIST.getValue());
        subscribe.setAdminId(house.getAdminId());
        houseSubscribeRespository.save(subscribe);
        return  ServiceResult.success();
    }

    /**
     *
     * @param status
     * @param start
     * @param size
     * @return
     */
    @Override
    public ServiceMultiResult<Pair<HouseDTO, HouseSubscribeDTO>> querySubscribeList(HouseSubscribeStatus status, int start, int size) {

        //获取Houseid
        Long userId = LoginUserUtil.getLoginUserId();
        //创建分页对象
        Pageable pageable = new PageRequest(start/size,size,new Sort(Sort.Direction.DESC,"createTime"));
        Page<HouseSubscribe> page = houseSubscribeRespository.findAllByUserIdAndStatus(userId, status.getValue(), pageable);

        return wrapper(page);
    }

    @Override
    @Transactional
    public ServiceResult subscribe(Long houseId, Date orderTime, String telephone, String desc) {
        Long userId = LoginUserUtil.getLoginUserId();
        HouseSubscribe subscribe = houseSubscribeRespository.findByHouseIdAndUserId(houseId, userId);
        if (subscribe == null){
            return new ServiceResult(false,"无预约记录");
        }
        if (subscribe.getStatus()!=HouseSubscribeStatus.IN_ORDER_LIST.getValue()){
            return new ServiceResult(false,"无法预约");
        }
        subscribe.setStatus(HouseSubscribeStatus.IN_ORDER_TIME.getValue());
        subscribe.setLastUpdateTime(new Date());
        subscribe.setTelephone(telephone);
        subscribe.setDesc(desc);
        subscribe.setOrderTime(orderTime);
        houseSubscribeRespository.save(subscribe);
        return ServiceResult.success();
    }

    @Override
    @Transactional
    public ServiceResult cancelSubcribe(Long houseId) {
        Long userId = LoginUserUtil.getLoginUserId();
        HouseSubscribe subscribe = houseSubscribeRespository.findByHouseIdAndUserId(houseId, userId);
        if (subscribe == null){
            return new ServiceResult(false,"无预约记录");
        }
        houseSubscribeRespository.delete(subscribe.getId());
        return ServiceResult.success();
    }

    @Override
    public ServiceMultiResult<Pair<HouseDTO, HouseSubscribeDTO>> findSubscribeList(int start, int size) {
        Long userId = LoginUserUtil.getLoginUserId();
        //第几页=开始位置/一页数量，每页数量 排序方式
        Pageable pageable = new PageRequest(start/size,size,new Sort(Sort.Direction.DESC,"orderTime"));
        Page<HouseSubscribe> page = houseSubscribeRespository.findAllByAdminIdAndStatus(userId, HouseSubscribeStatus.IN_ORDER_TIME.getValue(), pageable);

        return wrapper(page);
    }

    @Override
    @Transactional
    public ServiceResult finishSubscribe(Long houseId,Long userId) {
        Long adminId = LoginUserUtil.getLoginUserId();
        //查询houseSubscribe
        HouseSubscribe subscribe = houseSubscribeRespository.findByHouseIdAndAdminIdAndUserId(houseId, adminId,userId);
        if (subscribe==null){
            return new ServiceResult(false,"无预约记录");
        }
            if (subscribe.getStatus() == HouseSubscribeStatus.IN_ORDER_TIME.getValue()){
                houseSubscribeRespository.updateStatus(subscribe.getId(),HouseSubscribeStatus.FINISH.getValue());
            }


        houseRepository.updateWatchTimes(houseId);
        return ServiceResult.success();
    }

//    @Override
//    public ServiceResult findDistrict(String cityEnName, String regionEnName) {
//        List<House> houses = houseRepository.findAllByCityEnNameAndRegionEnName(cityEnName, regionEnName);
//
//        houses.forEach(house -> {
//
//        });
//        return null;
//    }

    /**
     * 包装方法，方便代码复用
     * @param page
     * @return
     */
    private ServiceMultiResult<Pair<HouseDTO,HouseSubscribeDTO>>  wrapper(Page<HouseSubscribe> page){
        List<Pair<HouseDTO, HouseSubscribeDTO>> result = new ArrayList<>();
        if (page.getSize()<1){
            return new ServiceMultiResult<>(page.getTotalElements(),result);
        }
        List<HouseSubscribeDTO> subscribeDTOS = new ArrayList<>();
        List<Long> houseIds = new ArrayList<>();
        page.forEach(houseSubscribe -> {
            subscribeDTOS.add(modelMapper.map(houseSubscribe,HouseSubscribeDTO.class));
            houseIds.add(houseSubscribe.getHouseId());
        });
        Map<Long,HouseDTO> idToHouseMap = new HashMap<>();
        Iterable<House> houses = houseRepository.findAll(houseIds);
        houses.forEach(house -> {
            idToHouseMap.put(house.getId(),modelMapper.map(house,HouseDTO.class));
        });
        for (HouseSubscribeDTO subscribeDTO : subscribeDTOS) {
            Pair<HouseDTO,HouseSubscribeDTO> pair  = Pair.of(idToHouseMap.get(subscribeDTO.getHouseId()),subscribeDTO);
            result.add(pair);
        }
        return new ServiceMultiResult<>(page.getTotalElements(),result);
    }
    /**
     * 渲染详细信息及标签
     * @param houseIds
     * @param idToHouseMap
     */
    private void wrapperHouseList(List<Long> houseIds,Map<Long,HouseDTO> idToHouseMap){
        List<HouseDetail> allByHouseIdIn = houseDetailRepository.findAllByHouseIdIn(houseIds);
        allByHouseIdIn.forEach(houseDetail -> {
            HouseDTO houseDTO = idToHouseMap.get(houseDetail.getHouseId());
            HouseDetailDTO detailDTO = modelMapper.map(houseDetail,HouseDetailDTO.class);
            houseDTO.setHouseDetail(detailDTO);
        });
        List<HouseTag> houseTags = houseTagRepository.findAllByHouseIdIn(houseIds);
        houseTags.forEach(houseTag -> {
            HouseDTO houseDTO = idToHouseMap.get(houseTag.getHouseId());;
            houseDTO.getTags().add(houseTag.getName());
        });


    }

    private ServiceMultiResult<HouseDTO> simpleQuery(RentSearch rentSearch){
        Sort sort = HouseSort.generateSort(rentSearch.getOrderBy(),rentSearch.getOrderDirection());
        int page = rentSearch.getStart()/rentSearch.getSize();
        Pageable pageable = new PageRequest(page,rentSearch.getSize(),sort);
        Specification<House> specification = (root,criteriaQuery,criteriaBuilder) ->{
            Predicate predicate = criteriaBuilder.equal(root.get("status"),
                    HouseStatus.PASSES.getValue());
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("cityEnName"),rentSearch.getCityEnName()));
            if (HouseSort.DISTANCE_TO_SUBWAY_KEY.equals(rentSearch.getOrderBy())){
                //防止没有地铁距离的房源排在前面
                predicate = criteriaBuilder.and(predicate,criteriaBuilder.gt(root.get(HouseSort.DISTANCE_TO_SUBWAY_KEY),-1));
            }
            return predicate;
        };
        Page<House> houses = houseRepository.findAll(specification, pageable);
        List<HouseDTO> houseDTOS = new ArrayList<>();

        List<Long> houseIds = new ArrayList<>();
        Map<Long,HouseDTO> idToHouseMap = Maps.newHashMap();
        houses.forEach(house -> {

            HouseDTO houseDTO = modelMapper.map(house,HouseDTO.class);
            houseDTO.setCover(this.cdnPrefix+house.getCover());

            houseDTOS.add(houseDTO);
            houseIds.add(house.getId());
            idToHouseMap.put(house.getId(),houseDTO);
        });


        wrapperHouseList(houseIds,idToHouseMap);
        return new ServiceMultiResult<>(houses.getTotalElements(),houseDTOS);
    }

    /**
     * 图片信息填充
     * @param form
     * @param houseId
     * @return
     */
    private  List<HousePicture> generatePictures(HouseForm form,Long houseId){
        ArrayList<HousePicture> pictures = new ArrayList<>();
        if (form.getPhotos() == null || form.getPhotos().isEmpty()){
            return pictures;
        }
        //将表单类中的图片数据集合循环封装
        for (PhotoForm photoForm : form.getPhotos()) {
            HousePicture picture = new HousePicture();
            picture.setHouseId(houseId);
            picture.setCdnPrefix(cdnPrefix);
            picture.setPath(photoForm.getPath());
            picture.setWidth(photoForm.getWidth());
            picture.setHeight(photoForm.getHeight());
            pictures.add(picture);
        }
        return pictures;
    }


    /**
     * 房源信息填充
     * @param houseDetail
     * @param houseForm
     * @return
     */
    private ServiceResult<HouseDTO> wrapperDetailInfo(HouseDetail houseDetail,HouseForm houseForm){
        //检查form表中地铁线路信息
        Subway subway = subwayRepository.findOne(houseForm.getSubwayLineId());
        //没有查到
        if (subway == null){
            return new ServiceResult<>(false,"Not valid subway line!");
        }
        //检查地铁线路站点信息
        SubwayStation subwayStation = subwayStationRepository.findOne(houseForm.getSubwayStationId());
       if (subwayStation == null || subway.getId() != subwayStation.getSubwayId()){
           return  new ServiceResult<>(false,"Not valid subway station!");
       }
       houseDetail.setSubwayLineId(subway.getId());
       houseDetail.setSubwayLineName(subway.getName());
       houseDetail.setSubwayStationId(subwayStation.getId());
       houseDetail.setSubwayStationName(subwayStation.getName());
        //描述
       houseDetail.setDescription(houseForm.getDescription());
       //详细地址
       houseDetail.setDetailAddress(houseForm.getDetailAddress());
      //位置描述
       houseDetail.setLayoutDesc(houseForm.getLayoutDesc());
       //租用方式
       houseDetail.setRentWay(houseForm.getRentWay());
      //周边服务
       houseDetail.setRoundService(houseForm.getRoundService());
       //交通情况
       houseDetail.setTraffic(houseForm.getTraffic());

       return null;
    }

    @Override
    public ServiceResult<String> findRegion(String district) {
        if (district==null){
            return new ServiceResult<>(false,"Not valid district!");
        }
        String allRegionEnNameByDistrict = houseRepository.findAllRegionEnNameByDistrict(district);


        return new ServiceResult<>(true,allRegionEnNameByDistrict);
    }
}
